package com.cf.r971;

import java.io.*;

public class f {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer in = new StreamTokenizer(br);
        PrintWriter out = new PrintWriter(System.out);
        in.nextToken(); int t = (int) in.nval;
        while (t-- > 0) {
            in.nextToken();
            long n = (long) in.nval;
            in.nextToken();
            long k = (long) in.nval;
            long sum = n * (2 * k + n - 1) / 2;

            long l = 0, r = n;
            while (l < r) {
                long mid = (l + r + 1) >>> 1;
                if (mid * (mid + 2 * k - 1) <= sum) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            }
            long i0 = l;

            long p0 = i0 * (2 * k + i0 - 1) / 2;
            long p1 = (i0 + 1) * (2 * k + i0) / 2;

            long ans0 = Math.abs(2 * p0 - sum);
            long ans2 = Math.abs(2 * p1 - sum);

            out.println(Math.min(ans0, ans2));
        }
        out.flush();
        out.close();
        br.close();
    }
}
